const { contextBridge, ipcRenderer } = require('electron')
const handleSend = async (vue_params) => {
  let fallback = await ipcRenderer.invoke('sent-event', vue_params)
  return fallback
}
let selectPath = async function selectInstallPath() {
  try {
    const path = await ipcRenderer.invoke('open-select-path-dialog')
    if (path && !path.canceled) {
      console.log('主进程返回的路径:', path.filePaths[0])
      // 此处的 `this` 上下文不再使用 Vue 实例
      return path.filePaths[0]
    } else {
      console.log('用户取消了路径选择')
      return null
    }
  } catch (error) {
    console.error('路径选择过程中发生错误:', error)
    return null
  }
}

contextBridge.exposeInMainWorld('myApi', {
  handleSend: handleSend,
  selectPath: selectPath,
  // 能暴露的不仅仅是函数，我们还可以暴露变量

  //下载文件
  downloadFile: (fileUrl, outputFileName, outputFileAddress) => {
    ipcRenderer
      .invoke('download-file', { fileUrl, outputFileName, outputFileAddress })
      .then((outputPath) => {
        console.log('文件已成功下载到临时目录:', outputPath)
        // 这里可以调用 window.postMessage 或其他方式将消息发回渲染进程
        // 例如：window.webContents.send('download-completed', outputPath);
      })
      .catch((error) => {
        console.error('下载失败:', error)
      })
  },
  //下载进度
  listenDownloadProgress: (callback) => {
    ipcRenderer.on(
      'download-progress',
      (event, { progress, speed, remainingTime, receivedBytes, totalBytes }) => {
        callback(progress, speed, remainingTime, receivedBytes, totalBytes)
      }
    )
  },

  // 最小化
  windowMin: () => {
    ipcRenderer.send('window-min')
  },
  // 最大化
  windowMax: () => {
    ipcRenderer.send('window-max')
  },
  // 关闭窗口
  windowClose: () => {
    ipcRenderer.send('window-close')
  },
  //打开子页面
  openChildWindow: () => {
    ipcRenderer.send('open-child-window')
  },
  //取消下载
  cancelDownload: () => {
    ipcRenderer.send('cancel-download')
  },
  //暂停下载
  pauseDownload: () => {
    ipcRenderer.send('pause-download')
  },
  //恢复下载
  resumeDownload: () => {
    ipcRenderer.send('resume-download')
  },
  //通知：用户取消下载
  userCanceled: (callback) => {
    ipcRenderer.on('user-canceled', (event, data) => {
      console.log(data.message)
      callback(data.canceled)
    })
  }
})
